<template>
  <div class="flex h-full overflow-hidden">
    <div class="bg-[#E0EEFA] h-full flex flex-col" :class="!isShowLeft ? 'w-0 p-0' : 'px-4 py-6 w-[280px]'">
      <div class="px-3 py-2 bg-[#FFFFFF]/40 rounded-[6px] flex justify-between items-center">
        <div class="flex items-center">
          <img class="mr-2" src="@/assets/images/ai.png" alt="">
          <span class="font-[600] text-[16px] leading-6">智慧分析大模型</span>
        </div>
        <div class="text-custom-blue cursor-pointer" v-if="activeName === '2'">
          <el-icon @click="createNewRecord">
            <Plus />
          </el-icon>
        </div>
      </div>
      <div class="h-16 w-full px-6 leading-[64px] rounded-[6px] mb-4 font-[600] text-[16px]">
        <span :class="activeName === '1' ? 'tab-active-item' : 'tab-item'" @click="changeTabs('1')">考核任务记录</span>
        <span :class="activeName === '2' ? 'tab-active-item' : 'tab-item'" @click="changeTabs('2')">对话记录</span>
      </div>
      <div class="flex mb-6">
        <el-input v-if="activeName === '1'" class="input mr-2" v-model="taskRecordValue" placeholder="请输入考核任务"
          :prefix-icon="Search" @input="getTaskRecords" />
        <el-input v-else class="input mr-2" v-model="inputValue" placeholder="请输入对话记录" :prefix-icon="Search"
          @input="getDialogList" />
        <!-- <div class="bg-white/30 p-2 rounded-[6px] leading-none"> -->
        <!-- <el-icon><Delete /></el-icon> -->
        <!-- </div> -->
      </div>
      <div v-if="activeName === '2'" class="flex-1 overflow-auto">
        <div class="px-3 py-2 leading-[22px] rounded-[6px] cursor-pointer mb-2" v-for="item in recordsLists"
          :key="item.id" :class="[
            activeTask === item.id ? 'bg-white text-custom-text' : 'text-custom-text-65',
            editInputTask === item.id ? 'bg-white text-custom-text border border-solid border-[#33A0FF]' : 'text-custom-text-65'
          ]" @click="taskDetail(item)">
          <div v-if="editInputTask !== item.id" class="flex justify-between items-center"
            @mouseenter="isShowEditIcon = true; hoverTask = item.id" @mouseleave="isShowEditIcon = false">
            <div class="text-[14px]">
              {{ item.name || '-' }}
            </div>
            <div v-if="isShowEditIcon && hoverTask === item.id">
              <el-icon class="mx-[10px] hover:text-custom-blue" color="rgba(0,0,0,0.65)"
                @click.stop="editInputTask = item.id; taskNameValue = item.name">
                <EditPen />
              </el-icon>
              <el-icon @click.stop="deleteRecords(item)" color="#FC474C">
                <Delete />
              </el-icon>
            </div>
          </div>
          <div v-else class="flex justify-between items-center h-[22px]">
            <div>
              <el-input v-model="taskNameValue" class="taskIptStyle" style="width: 170px;" placeholder="请输入新名称" />
            </div>
            <div>
              <el-icon @click.stop="updateRecords('name')" class="mx-[10px]">
                <Check />
              </el-icon>
              <el-icon @click.stop="editInputTask = ''">
                <Close />
              </el-icon>
            </div>
          </div>

        </div>
      </div>
      <div v-else class="flex-1 overflow-auto">
        <div class="px-3 py-2 leading-[22px] rounded-[6px] cursor-pointer mb-2" v-for="item in recordsLists"
          :key="item.id" :class="[
            activeTask === item.id ? 'bg-white text-custom-text' : 'text-custom-text-65'
          ]" @click="getTaskRecordsDetail(item)">
          <div class="flex justify-between items-center">
            <div class="text-[14px]">
              {{ item.name || '-' }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-1 h-full bg-[#F5FBFF] py-8 relative flex justify-center">
      <img class="absolute top-0 right-0" src="@/assets/images/image_2570.png" alt="">
      <img class="absolute left-0 bottom-0" src="@/assets/images/image_2571.png" alt="">
      <img class="absolute left-48 bottom-24 h-[142px] z-10" src="@/assets/home/GIF-loop.gif" alt="" v-if="isDialogLoop">
      <img class="absolute left-48 bottom-24 h-[142px] z-10" src="@/assets/home/GIF-end.gif" alt="" v-else>
      <div
        class="absolute top-0 right-0 px-4 py-[6px] mt-7 mr-7 rounded-[6px] text-custom-blue bg-[#33A0FF]/10 flex items-center cursor-pointer"
        @click="goBack">
        <el-icon class="mr-1">
          <Back />
        </el-icon>
        返回
      </div>
      <div class="absolute top-[45%] left-[-2px] z-10 cursor-pointer" :class="!isShowLeft ? 'rotate-180' : ''"
        @click="handleHideLeft">
        <img src="@/assets/images/Frame_1410068169.png" alt="">
      </div>
      <div class="flex flex-col h-full relative w-3/5">
        <!-- <div class="flex justify-center mb-7">
        <div class="px-4 py-[6px] rounded-[6px] text-custom-blue bg-[#33A0FF]/10 border-2 border-solid border-[#33A0FF]/[0.16]">智慧分析大模型1.0</div>
      </div> -->
        <div class="flex-1 overflow-auto mt-10 mb-4 scrollbar" ref="scrollDiv">
          <div class="flex items-center mb-6" v-if="activeName === '2'">
            <img class="mr-[10px]" src="@/assets/images/ai.png" alt="">
            <div class="px-4 py-3 rounded-[6px] bg-white shadow-[0_2px_4px_0px_rgba(0,0,0,0.06)]">
              <span class="text-custom-text leading-[22px] mb-4">你好，我是你的智能问答助手！我可以为你解答相关问题，请告诉你的问题！</span>
            </div>
          </div>
          <div v-for="(item, index) in conversation" :key="index">
            <div v-if="item.isShowResult" class="mb-6">
              <div class="flex items-center mb-6" v-if="activeName === '1' && !!taskRecordsDetail.name">
                <img class="mr-[10px]" src="@/assets/images/ai.png" alt="">
                <div class="px-4 py-3 rounded-[6px] bg-white shadow-[0_2px_4px_0px_rgba(0,0,0,0.06)]">
                  <span class="text-custom-text leading-[22px] mb-4">
                    在{{ taskRecordsDetail.name }}考核中，你已经通过{{ taskRecordsDetail.pass_chapter_num }}个章节、累计获得{{
                      taskRecordsDetail.score }}分;
                    您上次考核时间为{{ taskRecordsDetail.last_test_time || '-' }}
                    <span v-if="taskRecordsDetail.ddl > 0">，距离考核截止时间还有{{ filterTime(taskRecordsDetail.ddl)
                    }}；</span>
                    <span v-else-if="taskRecordsDetail.ddl == 0">，此考核已经截止；</span>
                    <span v-else></span>
                    您已成功掌握{{ taskRecordsDetail.mastered_point_number }}个知识点，还有{{
                      taskRecordsDetail.problem_point_number
                    }}个知识点未掌握，以下是推荐课程；
                    加油！
                  </span>
                </div>
              </div>
              <div
                v-if="activeName === '1' && !!taskRecordsDetail.name && taskRecordsDetail.problem_points && taskRecordsDetail.problem_points.length > 0">
                <courseCard v-if="taskRecordsDetail.problem_points" :cardParams="{
                  points: problem_points
                }"></courseCard>
              </div>
            </div>
            <div v-else>

              <div v-if="item.question">
                <div class="flex items-center justify-end mb-6">
                  <div class="px-4 py-3 rounded-[6px] mr-[10px] bg-custom-blue shadow-[0_2px_4px_0px_rgba(0,0,0,0.06)]">
                    <span class="text-custom-text leading-[22px] mb-4 text-white">{{ item.question }}</span>
                  </div>
                  <img src="@/assets/images/head.png" alt="">
                </div>
                <div class="flex items-start justify-start mb-6">
                  <img class="mr-[10px]" src="@/assets/images/ai.png" alt="">
                  <div class="w-full break-all">
                    <div v-if="item.answer"
                      class="px-4 py-3 mb-4 rounded-[6px] bg-white shadow-[0_2px_4px_0px_rgba(0,0,0,0.06)]">
                      <div class="text-custom-text leading-[22px] mb-4" v-html="item.answer"></div>
                      <div class="flex justify-between items-center">
                        <div class="text-custom-text-65 flex items-center cursor-pointer" @click="toCopy(item.answer)">
                          <img src="@/assets/images/file-copy-line.png" alt="">
                          <span>复制</span>
                        </div>
                        <div class="flex cursor-pointer">
                          <img class="rotate-180 mr-5" src="@/assets/images/thumbs-down2.png" alt="">
                          <img src="@/assets/images/thumbs-down2.png" alt="">
                        </div>
                      </div>
                    </div>
                    <div v-else>
                      <div class="px-4 py-3 mb-4 rounded-[6px] bg-white shadow-[0_2px_4px_0px_rgba(0,0,0,0.06)]">
                        <div class="text-custom-text leading-[22px] mb-4">思考中...</div>
                      </div>
                    </div>
                    <div v-if="activeName === '1' && !!item.currentAnswerIds">
                      <courseCard v-if="!!item.currentAnswerIds" :cardParams="{
                        points: item.currentAnswerIds
                      }"></courseCard>
                    </div>
                    <!-- <div class="grid grid-cols-3 gap-3" v-if="item.recommend && item.recommend.length">
                    <div class="bg-white border border-custom-border overflow-hidden cursor-pointer rounded-[6px]"
                      v-for="child in item.recommend" :key="child.id" @click="handleCardClick(child)">
                      <div class="w-full h-[172px] bg-no-repeat bg-auto bg-center p-[10px]"
                        :style="'background-image: url(' + child.cover + ');'">
                        <span
                          class="text-white text-sm px-2 py-0.5 bg-gradient-to-r h-6 w-14 rounded-[4px] mr-1 from-[#33C9FF] to-[#33A0FF]">
                          {{ child.name }}
                        </span>
                      </div>
                      <div class="px-4 py-4">
                        <p class="text-custom-text text-base font-semibold py-4">{{ child.name }}</p>
                        <div class="flex items-center justify-between">
                          <span class="flex items-center gap-2">
                            <img src="@/assets/images/eye-fill.png" alt="">
                            <span>{{ child.students || 0 }}</span>
                          </span>
                        </div>
                      </div>
                    </div>
                  </div> -->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <div
            class="flex flex-col bg-white p-4 h-[120px] rounded-[8px] mb-2 border-2 border-solid shadow-[0_2px_8px_4px_rgba(0,0,0,0.06)]"
            :class="isFocus ? 'border-[#33A0FF]' : 'border-[#FFFFFF]/[0.6]'">
            <div class="flex-1">
              <el-input class="send-input" v-model="questionInput" style="width: 100%;" type="textarea"
                placeholder="使用“/”使用模板指令，可通过Shift+Enter换行" @blur="isFocus = false" @focus="isFocus = true" />
            </div>
            <div class="flex justify-between align-center">
              <div class="flex align-center">
                <!--              <div class="bg-[#F5F5F5] rounded-[6px] px-2 py-1 mr-2 flex items-center cursor-pointer">-->
                <!--                <img class="mr-1" src="@/assets/images/movie-line.png" alt="">-->
                <!--                <span>视频</span>-->
                <!--              </div>-->
                <!-- <UploadComponent
                  uploadType="video"
                  uploadUrl="https://example.com/upload/image"
              />
              <UploadComponent
                  uploadType="image"
                  uploadUrl="https://example.com/upload/image"
              /> -->
              </div>
              <div class="bg-gradient-to-r from-[#33A0FF] to-[#33DAFF] px-3 py-[6px] rounded-[6px] cursor-pointer"
                @click="httpMessage" @keyup.enter.native="httpMessage">
                <img src="@/assets/images/send.png" alt="">
              </div>
            </div>
          </div>
          <div class="text-[12px] text-custom-text/25 text-center">
            内容由AI生成，无法确保真实准确，仅供参考，请遵守《情感智探-用户协议》、《情感智探-个人信息保护规则》，基于情感大模型，版本：V1.0.0
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Back, Check, Close, Delete, EditPen, Plus, Search } from "@element-plus/icons-vue";
import { ElMessage, ElLoading } from 'element-plus'
import useClipboard from 'vue-clipboard3'
import { computed, onMounted, ref, onUnmounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { StorageUtil, TokenUtil } from "@/utils/common";
import { useMenuStore } from "@/stores/menu";
import { chatApi } from "@/api/index";
import MarkdownIt from 'markdown-it'
import courseCard from '../examCourses/components/courseCard.vue'
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
// 加载 duration 插件
dayjs.extend(duration);
const md = new MarkdownIt()
const { toClipboard } = useClipboard()
const route = useRoute()
const router = useRouter()
const menuStore = useMenuStore();
const isFocus = ref(false)
const inputValue = ref('')
const taskRecordValue = ref('')
const taskNameValue = ref('')
const activeName = ref('1')
const activeTask = ref('1')
const hoverTask = ref('1')
const editInputTask = ref('')
const questionInput = ref('')
const questionValue = ref('')
const taskRecordsDetail = ref({})
const problem_points = ref('')
const isDialogLoop = ref(false)
const isShowLeft = ref(true)
const isShowEditIcon = ref(false)
const recordsLists = ref([])
const conversation = ref([])
const scrollDiv = ref(null)
const xmlhttp = new XMLHttpRequest()
const currentAnswer = ref('')
const currentAnswerIds = ref('')


const userInfo = computed(() => {
  return StorageUtil.local.get('user')?.userInfo || {}
})
onMounted(() => {
  if (activeName.value === '1') {
    getTaskRecords()
  } else {
    getDialogList()
  }

  window.addEventListener('keydown', keyDown)
})
onUnmounted(() => {
  //销毁事件
  window.removeEventListener('keydown', keyDown, false)
});
//点击回车键
const keyDown = (e) => {
  if ((e.keyCode == 13 || e.keyCode == 100) && !e.shiftKey) {
    httpMessage()
  }
}

// 创建新对话
const createNewRecord = () => {
  const randomId = Math.random().toString(6).substr(2);
  const newRecord = {
    id: randomId,
    isNew: true,
    name: '新对话',
    create_time: new Date().toISOString() // 添加创建时间
  };

  // 将新记录添加到列表并重新排序
  recordsLists.value = sortRecordsByTime([newRecord, ...recordsLists.value]);
  activeTask.value = randomId;
  conversation.value = [
    {
      id: randomId,
      isNew: true,
      question: '',
      answer: '',
      recommend: []
    }
  ];
  // createRecords();
};

// 首先定义排序方法
const sortRecordsByTime = (records) => {
  return records.sort((a, b) => {
    const timeA = new Date(a.create_time).getTime();
    const timeB = new Date(b.create_time).getTime();
    return timeB - timeA; // 降序排列，最新的在前
  });
};

// 获取考核任务列表
const getTaskRecords = () => {
  const params = { keyword: taskRecordValue.value }
  chatApi.getTaskRecords(params).then(res => {
    // 对结果进行排序
    recordsLists.value = res || [];
    // 如果有记录，则选择第一条记录
    if (recordsLists.value.length > 0) {
      // activeTask.value = recordsLists.value[0].id;
      let obj = {}
      const defaultDialog = sessionStorage.getItem('defaultDialog') || '{}'
      const { testId } = JSON.parse(defaultDialog)
      if (testId) {
        obj = recordsLists.value.find(item => item.id == testId) || {};
      } else {
        obj = recordsLists.value[0] || {};
      }
      activeTask.value = obj.id
      getTaskRecordsDetail(obj);
    }
  })
}

// 获取会话记录列表
const getDialogList = () => {
  const params = {
    page: 1,
    page_size: 9999,
    type: activeName.value,
    name: inputValue.value,
    user_id: userInfo.value.id + ''
  }
  chatApi.getDialogList(params).then(res => {
    // 对结果进行排序
    recordsLists.value = sortRecordsByTime(res);
    // 如果有记录，则选择第一条记录
    if (recordsLists.value.length > 0) {
      activeTask.value = recordsLists.value[0].id;
      taskDetail(recordsLists.value[0]);
    } else {
      if (!inputValue.value) {
        createNewRecord()
      }
    }
  }).catch(error => {
    ElMessage.error('获取记录列表失败');
  });
};

//原生http获取message
const httpMessage = () => {
  if (!questionInput.value) {
    ElMessage.error('请输入问题')
    return
  }
  questionValue.value = JSON.parse(JSON.stringify(questionInput.value))
  const loading = ElLoading.service({
    spinner: 'homeLoading',
    text: '',
    background: 'rgba(0, 0, 0, 0)',
  })
  const { id } = userInfo.value
  let params = {}
  if (activeName.value === '1') {
    params = {
      inputs: {
        create_id: taskRecordsDetail.value.id,
        token: `${TokenUtil.getToken()}`
      },
      query: questionInput.value,
      // response_mode: "blocking",
      response_mode: "streaming",
      conversation_id: '',
      user: "abc-123",
      files: []
    }
  } else {
    params = {
      inputs: { create_id: id },
      query: questionInput.value,
      // response_mode: "blocking",
      response_mode: "streaming",
      conversation_id: '',
      user: "abc-123",
      files: []
    }
  }

  conversation.value.push({
    id: '',
    question: questionInput.value,
    answer: '',
    recommend: ''
  })
  questionInput.value = ''
  scrollToBottom()

  xmlhttp.onreadystatechange = () => {
    if (xmlhttp.readyState == XMLHttpRequest.DONE == true) {
      loading.close()
      if (conversation.value[0].isNew) {//&& activeName.value === '2'
        createRecords()
      } else {
        updateRecords('history')
      }
      setTimeout(() => {
        isDialogLoop.value = false;
      }, 100)
    }
    if (xmlhttp.readyState == 3 || xmlhttp.readyState == 4) {
      let newdata = xmlhttp.responseText
      if (newdata) {
        isDialogLoop.value = true;
        let chunks = newdata.split("data: ")
        var str = ""
        var list = chunks
        list.forEach((chunk, index) => {
          if (chunk.length > 0) {
            var chunkstr = chunk.slice(0, -1)
            try {
              var chunkdic = JSON.parse(chunkstr)
              str += chunkdic["text"]
            } catch {
            }
            const { htmlContent, jsonData } = parseFormattedString(str);
            let htmlText = htmlContent.replace(/^### (.*)$/gm, '<h3>$1</h3>');
            htmlText = htmlText.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>');
            // activeTask.value = id
            if (activeName.value === '1') {
              currentAnswer.value = htmlText
              conversation.value[conversation.value.length - 1] = {
                // id: id,
                question: questionValue.value,
                answer: removeBetweenAmpersands(htmlText),
                oldAnswer: str,
                recommend: jsonData?.video || [],
                currentAnswerIds: extractNumbers(currentAnswer.value)
              }
            } else {
              conversation.value[conversation.value.length - 1] = {
                // id: id,
                question: questionValue.value,
                answer: htmlText,
                oldAnswer: str,
                recommend: jsonData?.video || []
              }
            }
            scrollToBottom()
          }
        })
      }
    }
  }
  if (activeName.value === '1') {
    xmlhttp.open("post", "http://alone.hndfdz.cn:7799/v1/chat-assessment", true)
  } else {
    xmlhttp.open("post", "http://alone.hndfdz.cn:7799/v1/chat-messages", true)
  }
  xmlhttp.responseType = 'text'
  xmlhttp.setRequestHeader('Content-Type', "application/json")
  // xmlhttp.setRequestHeader('Accept', 'text/event-stream')
  xmlhttp.setRequestHeader('Authorization', 'Bearer app-aK9ohWBEtIRCGu7wvIFQiE9b');
  xmlhttp.send(JSON.stringify(params))

}

function extractNumbers(str) {
  const startIndex = str.indexOf('&');
  if (startIndex === -1) return '';

  const endIndex = str.indexOf('&', startIndex + 1);
  if (endIndex === -1 || endIndex <= startIndex + 1) return '';

  return str.substring(startIndex + 1, endIndex);
}
function removeBetweenAmpersands(str) {
  const startIndex = str.indexOf('&');
  if (startIndex === -1) return str;

  const endIndex = str.indexOf('&', startIndex + 1);
  if (endIndex === -1) return str;

  return str.slice(0, startIndex) + str.slice(endIndex + 1);
}

const parseJson = (str) => {
  // 定义正则表达式，用于匹配 JSON 对象
  const regex = /\{.*?\}/g;
  // 使用 match 方法找到所有匹配的 JSON 对象
  const matches = str.match(regex);
  if (!matches) {
    return [];
  }
  const dataValues = [];
  // 遍历每个匹配的 JSON 对象
  for (const match of matches) {
    try {
      // 将 JSON 字符串解析为 JavaScript 对象
      const obj = JSON.parse(match);
      // 如果对象中存在 data 属性，则将其值添加到 dataValues 数组中
      if (obj.hasOwnProperty('data')) {
        dataValues.push(obj.data);
      }
    } catch (error) {
      // 处理 JSON 解析错误
      console.error(`Error parsing JSON: ${match}`, error);
    }
  }
  return dataValues;
}

const scrollToBottom = () => {
  nextTick(() => {
    const container = scrollDiv.value;
    container.scrollTop = container.scrollHeight;
  })
};
//获取对话详情
const taskDetail = (item) => {
  taskNameValue.value = item.name
  activeTask.value = item.id
  conversation.value = []
  const url = activeName.value === '1' ? 'getTaskRecordsDialogDetail' : 'getRecordsDetail'
  chatApi[url](item.id).then(res => {
    if (activeName.value === '1') {
      if (!res.content) {
        conversation.value = [
          {
            id: Math.random().toString(6).substr(2),
            isNew: true,
            question: '',
            answer: '',
            recommend: []
          }
        ];
        conversation.value.push({
          isShowResult: true,
        })
        scrollToBottom()
      } else {
        res.content.forEach(el => {
          const { htmlContent, jsonData } = parseFormattedString(el.answer);
          const obj = {
            id: res.id,
            question: el.question,
            answer: htmlContent,
            oldAnswer: el.answer,
            recommend: jsonData ? jsonData.video : [],
            currentAnswerIds: el.currentAnswerIds || ''
          }
          conversation.value.push(obj)
        });
        conversation.value.push({
          isShowResult: true,
        })
        scrollToBottom()
      }
    } else {
      res.content.forEach(el => {
        const { htmlContent, jsonData } = parseFormattedString(el.answer);
        const obj = {
          id: res.id,
          question: el.question,
          answer: htmlContent,
          oldAnswer: el.answer,
          recommend: jsonData ? jsonData.video : []
        }
        conversation.value.push(obj)
      });
      scrollToBottom()
    }
    const defaultDialog = sessionStorage.getItem('defaultDialog') || '{}'
    const { text } = JSON.parse(defaultDialog)
    if (text) {
      questionInput.value = text
      httpMessage()
      sessionStorage.removeItem('defaultDialog')
    }
    scrollToBottom()

  })
}

//查询考核任务详情 
const getTaskRecordsDetail = (item) => {
  if (!item.id) {
    return
  }
  activeTask.value = item.id
  taskRecordsDetail.value.problem_points = null
  chatApi.getTaskRecordsDetail(item.id).then(res => {
    taskRecordsDetail.value = res
    problem_points.value = res.problem_points.join(',')
    taskDetail(item)
  })
}


//创建历史记录
const createRecords = () => {
  const content = conversation.value.filter(item => {
    if (item.question) {
      return {
        question: item.question,
        answer: item.oldAnswer
      }
    }
  })
  let params = {}
  if (activeName.value === '1') {
    params = {
      id: taskRecordsDetail.value.id + '',
      user_id: userInfo.value.id + '',
      name: taskRecordsDetail.value.name,
      content: content
    }
  } else {
    params = {
      user_id: userInfo.value.id + '',
      type: activeName.value,
      name: questionValue.value ? questionValue.value : '新对话',
      content: content
    }
  }
  const url = activeName.value === '1' ? 'createTaskRecords' : 'createRecords'
  chatApi[url](params).then(res => {
    questionInput.value = ''
    if (activeName.value === '2') {
      getDialogList()
    }
    // else {
    //   getTaskRecords()
    // }
  })
}

// 删除历史记录
const deleteRecords = (item) => {
  if (item.isNew) {
    recordsLists.value = recordsLists.value.filter(item => !item.isNew)
    getDialogList()
  } else {
    // const params = {
    //   user_id: userInfo.value.id + '',
    //   type: activeName.value,
    //   name: item.name,
    //   content:{
    //     question: item.content.question,
    //     answer: item.content.answer
    //   }
    // }
    chatApi.deleteRecords(item.id).then(res => {
      getDialogList()
    })
  }
}

// 更新历史记录名称
const updateRecords = (type) => {
  let params = {}
  const content = conversation.value.filter(item => !item.isShowResult)
  if (activeName.value === '1') {
    params = {
      user_id: userInfo.value.id + '',
      name: taskRecordsDetail.value.name,
      content: content
    }
  } else {
    params = {
      user_id: userInfo.value.id + '',
      type: activeName.value,
      name: taskNameValue.value,
      content: content
    }
  }
  const url = activeName.value === '1' ? 'updateTaskRecords' : 'updateRecords'
  chatApi[url](activeTask.value, params).then(res => {
    editInputTask.value = ''
    questionInput.value = ''
    if (type === 'name') getDialogList()
  })
}

// 解析格式化字符串
const parseFormattedString = (str = '') => {
  // 存储解析结果
  const result = {
    htmlContent: '',
    jsonData: null
  };

  try {
    // 1. 找到JSON数据部分
    const jsonMatch = str.match(/\{[\s\S]*\}/);
    const jsonString = jsonMatch ? jsonMatch[0] : null;

    // 2. 提取并解析JSON数据
    if (jsonString) {
      result.jsonData = JSON.parse(jsonString);
      // 移除原文中的JSON部分
      str = str.replace(jsonString, '');
    }

    // 3. 处理剩余文本转换为HTML
    const htmlContent = str
      // 处理换行符
      .split('\n')
      // 过滤空行
      .filter(line => line.trim())
      // 转换为HTML段落
      .map(line => {
        // 处理列表项
        if (line.startsWith('- ')) {
          return `<li>${line.substring(2)}</li>`;
        }
        return `<p>${line}</p>`;
      })
      .join('');

    // 给列表项添加ul标签包裹
    result.htmlContent = htmlContent.replace(
      /(<li>.*?<\/li>)+/g,
      match => `<ul>${match}</ul>`
    );

    return result;
  } catch (error) {
    return {
      htmlContent: '<p>解析错误</p>',
      jsonData: null
    };
  }
}

//一键复制
const toCopy = async (item) => {
  try {
    await toClipboard(item);
    ElMessage.success('复制成功')
  } catch (e) {
    console.error(e);
  }
}

//切换记录tab
const changeTabs = (type) => {
  activeName.value = type
  if (type === '1') {
    getTaskRecords()
  } else {
    getDialogList()
  }
}

const handleHideLeft = () => {
  isShowLeft.value = !isShowLeft.value
}

//返回
const goBack = () => {
  if (userInfo.value.user_type == '2' || userInfo.value.user_type == '3' || userInfo.value.user_type == '5') {
    menuStore.setActiveIndex('9');
    menuStore.setMenuType('4');
    router.push("/teacherAssessList");
  } else if (userInfo.value.user_type == '4') {
    menuStore.setActiveIndex('10');
    menuStore.setMenuType('5');
    router.push("/associationAssessList");
  } else {
    menuStore.setActiveIndex('1');
    menuStore.setMenuType('1');
    router.push("/");
  }
}

const handleCardClick = (row) => {
  StorageUtil.session.set('assessData', row)
  router.push({
    path: '/examCourses/assessDetail',
    query: {
      id: row.id,
      name: row.name
    }
  })
}

//过滤时间
const filterTime = (value) => {
  if (!value) return '';
  // 创建一个持续时间对象
  const dur = dayjs.duration(value, 'hours');

  // 获取整天数和剩余小时数
  const days = Math.floor(dur.asDays());
  const remainingHours = dur.hours();

  // 格式化结果
  return `${days}天${remainingHours}小时`;
}
</script>
<style scoped lang="scss">
.scrollbar::-webkit-scrollbar {
  display: none
}

:deep(.input) {
  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.3);
    box-shadow: none;
  }
}

:deep(.send-input) {
  .el-textarea__inner {
    box-shadow: none;
    resize: none
  }
}

:deep(.taskIptStyle) {
  .el-input__wrapper {
    padding: 0;
    box-shadow: none;
  }

  .el-input__inner {
    background: white;
  }
}
</style>